<?php

namespace App\Console\Commands;

use App\Contract\ContractStatus;
use App\Http\Service\DeviceService;
use App\Jobs\AutoPower;
use App\Model\Bill;
use App\Model\Contract;
use App\Model\DeviceBus;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class DeviceBusCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'device:bus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '设备自动分摊';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Log::info('开始派发公摊任务...');

        $chunkSize = 20; // 每批处理量
        $delayBetweenBatches = 3; // 批次间隔分钟数
        $delayWithinBatch = 3; // 批次内间隔秒数
        $totalProcessed = 0;
        $batchNumber = 0;

        DeviceBus::where('type', 1)
            ->orderBy('id')
            ->chunkById($chunkSize, function ($buses) use (&$batchNumber, &$totalProcessed, $delayBetweenBatches, $delayWithinBatch) {
                $batchStartTime = now()->addMinutes($batchNumber * $delayBetweenBatches);
                foreach ($buses as $k => $bus) {
                    $jobDelay = $batchStartTime->copy()->addSeconds($k * $delayWithinBatch);
                    dispatch(new AutoPower($bus->id))
                        ->delay($jobDelay);
                    $totalProcessed++;
                    Log::info(sprintf(
                        '批次 %d | 设备ID: %d | 计划执行时间: %s',
                        $batchNumber,
                        $bus->device_id,
                        $jobDelay->format('Y-m-d H:i:s')
                    ));
                }

                $batchNumber++;
            });
        Log::info("任务派发完成！总计: {$totalProcessed}个设备");
        return 0;
    }



}
